package br.ucb.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import br.ucb.bean.Disciplina;
import br.ucb.bean.Turma;
import br.ucb.dao.TurmaDAO;
import br.ucb.util.SimpleEntityManager;

public class TurmaController extends GenericController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private TurmaDAO turmaDAO;

	public TurmaDAO getTurmaDAO() {
		return turmaDAO;
	}

	public void setTurmaDAO(TurmaDAO turmaDAO) {
		this.turmaDAO = turmaDAO;
	}

	public void readyManagerAndDao() {
		setManager(new SimpleEntityManager("sacop"));
		this.turmaDAO = new TurmaDAO(getManager().getEntityManager());
		getManager().beginTransaction();
	}

	public List<Turma> findTurmas() {
		List<Turma> turmas;

		if (getProfessor() == null) {
			readyManagerAndDao();
			turmas = this.turmaDAO.listar();
			getManager().close();
		} else {
			List<Disciplina> disciplinas = new DisciplinaController()
					.findDisciplinas();
			readyManagerAndDao();
			turmas = findRelatedTurmas(disciplinas);
			getManager().close();
		}

		return turmas;
	}

	private List<Turma> findRelatedTurmas(List<Disciplina> disciplinas) {
		List<Turma> turmas = new ArrayList<Turma>();
		for (Disciplina disciplina : disciplinas) {
			turmas.addAll(this.turmaDAO.buscarRelacionado("disciplina.codigo",
					disciplina.getCodigo()));
		}
		return turmas;
	}

	public List<Turma> reconstructTurmas(List<Turma> turmas) {
		readyManagerAndDao();
		List<Turma> reconstructedTurmas = new ArrayList<Turma>();
		for (Turma turma : turmas) {
			reconstructedTurmas.add(this.turmaDAO.getById(turma.getCodigo()));
		}
		getManager().close();
		return reconstructedTurmas;
	}
	
	public Turma findById(int id){
		Turma turma;
		readyManagerAndDao();
		turma = getTurmaDAO().getById(id);
		getManager().close();
		return turma;
	}
}
